
package com.android.formula.task;

import android.content.ContentValues;
import android.content.Context;

import com.android.formula.common.MyApplication;
import com.android.formula.dao.NoteSubjectDao;
import com.android.formula.database.NoteDatabaseConnection;
import com.android.formula.model.NoteSubject;
import com.android.formula.utils.Constants;

public class SetNoteSubjectDBTask extends BaseDatabaseTask<NoteSubject, Integer> {

    public SetNoteSubjectDBTask(Context context, NoteSubject param, Class<Integer> responType,
            IDataEventHandler<Integer> dataEventHandler) {
        super(context, param, responType, dataEventHandler);
    }

    @Override
    protected Integer execute() {
        NoteDatabaseConnection dbcn = MyApplication.getDatabaseConnection();
        if (dbcn == null || mRequestParams == null) {
            return -1;
        }

        dbcn.open();
        NoteSubjectDao dao = new NoteSubjectDao(NoteSubject.class, mContext, dbcn.getDatabase());
        if (dao.isExistence(Constants.TABLE_SUBJECT_COL_SUBJECTID,
                "" + mRequestParams.getSubjectId())) {
            ContentValues cv = new ContentValues();
            cv.put(Constants.TABLE_SUBJECT_COL_SUBJECTNAME, mRequestParams.getSubjectName());

            dao.update(cv, Constants.TABLE_SUBJECT_COL_SUBJECTID,
                    "" + mRequestParams.getSubjectId());
        } else {
            mRequestParams.setSubjectId((int) dao.insert(mRequestParams));
        }
        dbcn.close();
        return mRequestParams.getSubjectId();
    }
}
